/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package summator;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author RERIR
 */
public class Summator extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Summator</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Summator at " + request.getContextPath() + "</h1>");
            out.println("<h1>Hello " + request.getParameter("user") + "!</h1>");            
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String user;
        Integer currentSum;
        Enumeration<String> headerNames = request.getHeaderNames();
        String header = "<p>";
        while (headerNames.hasMoreElements()) {
            String head = headerNames.nextElement();
            header += head + ":" + request.getHeader(head) + "<br>";
        }
        header += "</p>";
        
        response.setContentType("text/html;charset=UTF-8");
        String flagNewSession = "<p>It is old session</p>";
        HttpSession session = request.getSession(false);
        if (session == null) {
            session = request.getSession(true);
            flagNewSession = "<p>It is new session</p>";
            user = request.getParameter("user");
            session.setAttribute("user", user);
            currentSum = new Integer(0);
        }
        else {
            currentSum = (Integer)session.getAttribute("sum");
            if (currentSum == null) {
                flagNewSession = "<p>It is reuse old session</p>";
                user = request.getParameter("user");
                session.setAttribute("user", user);
                currentSum = new Integer(0);
            }
            else user = (String)session.getAttribute("user");
        }
        
        session.setAttribute("sum", currentSum);       
        
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Summator</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Summator at " + request.getContextPath() + "</h1>");
            out.println(flagNewSession);
            out.println(header);
            out.println("<h1>Hello " + user + "!</h1>");            
            out.println("<h1>Current SUM is " + currentSum + "!</h1>");
            out.println("<form action=\"Summator\" method=\"POST\"><p>Which add?&nbsp;");
            out.println("<input type=\"text\" name=\"number\" size=\"40\"></br>" + 
                    "<input type=\"submit\" value=\"Add\"></p><p><input type=\"submit\" value=\"Exit\"></p>"
                        + "<input type=\"hidden\" name=\"exit\" value=\"no\"></form>");
            out.println("<form action=\"Summator\" method=\"POST\"><p><input type=\"submit\" value=\"Exit\"><input type=\"hidden\" name=\"exit\" value=\"yes\"></p></form>");

            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }

    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession(false);
        
        if (session == null) {
            response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Session not valid 1");
            return;
        }
        
        Enumeration<String> headerNames = request.getHeaderNames();
        String header = "<p>";
        while (headerNames.hasMoreElements()) {
            String head = headerNames.nextElement();
            header += head + ":" + request.getHeader(head) + "<br>";
        }
        header += "</p>";
        

        
        if (request.getParameter("exit").equals("yes")) {
            PrintWriter out = response.getWriter();
            try {
                /*
                 * TODO output your page here. You may use following sample code.
                 */
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet Summator</title>");            
                out.println("</head>");
                out.println("<body>");
    //            out.println("<h1>Servlet Summator at " + request.getContextPath() + "</h1>");
                out.println("<h1>Bye " + session.getAttribute("user") + "!</h1>");            
                out.println("</body>");
                out.println("</html>");
                session.invalidate();

            } finally {            
                out.close();
            }
        }
        else {
            Integer i = (Integer)(session.getAttribute("sum"));
            String currentSum;
        
        
            try {
                i += Integer.parseInt((String)request.getParameter("number"));
                currentSum = i.toString();
            } catch (NumberFormatException e) {
                currentSum = "wrong number";
            }
            session.setAttribute("sum", i);

            PrintWriter out = response.getWriter();
            try {
                /*
                 * TODO output your page here. You may use following sample code.
                 */
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet Summator</title>");            
                out.println("</head>");
                out.println("<body>");
                out.println(header);
    //            out.println("<h1>Servlet Summator at " + request.getContextPath() + "</h1>");
                out.println("<h1>Hello " + session.getAttribute("user") + "!</h1>");            
                out.println("<h1>Current SUM is " + i + "</h1>");
                out.println(currentSum.equals("wrong number") ? "<p>Your number is wrong.  Sum didn't change.</p>" : "");
                out.println("<form action=\"Summator\" method=\"POST\"><p>Which add?&nbsp;");
                out.println("<input type=\"text\" name=\"number\" size=\"40\"></br>" + 
                    "<input type=\"submit\" value=\"Add\"></p><p><input type=\"submit\" value=\"Exit\"></p>"
                        + "<input type=\"hidden\" name=\"exit\" value=\"no\"></form>");
                out.println("<form action=\"Summator\" method=\"POST\"><p><input type=\"submit\" value=\"Exit\"><input type=\"hidden\" name=\"exit\" value=\"yes\"></p></form>");
                out.println("</body>");
                out.println("</html>");
            } finally {            
                out.close();
            }
       }

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Summator app";
    }// </editor-fold>
}
